// 蛇类
class Snake {
  constructor({ width = 20, height = 20, direction = 'right' } = {}) {
    this.element = []
    this.width = width
    this.height = height
    this.direction = direction

    this.body = [
      { x: 3, y: 2, color: 'red' },
      { x: 2, y: 2, color: 'blue' },
      { x: 1, y: 2, color: 'blue' },
    ]
  }

  // 移动的方向
  move (food, map) {
    let length = this.body.length - 1
    for (let i = length; i > 0; i--) {
      this.body[i].x = this.body[i - 1].x
      this.body[i].y = this.body[i - 1].y
    }

    let head = this.body[0]
    switch (this.direction) {
      case 'right':
        head.x += 1
        break;
      case 'left':
        head.x -= 1
        break;
      case 'top':
        head.y -= 1
        break;
      case 'bottom':
        head.y += 1
        break;
    }

    let headX = head.x * this.width
    let headY = head.y * this.height

    if (headX === food.x && headY === food.y) {
      let last = this.body[this.body.length - 1]
      this.body.push({
        y: last.x,
        y: last.y,
        color: last.color
      })

      food.render(map) // 重新生成食物
    }
  }

  render (map) {
    this.remove()

    let length = this.body.length
    for (let i = 0; i < length; i++) {
      const object = this.body[i];

      let div = document.createElement('div')
      map.appendChild(div)

      this.element.push(div)
      // 设置div样式
      div.style.position = 'absolute'
      div.style.width = this.width + 'px'
      div.style.height = this.height + 'px'
      div.style.left = object.x * this.width + 'px'
      div.style.top = object.y * this.height + 'px'
      div.style.backgroundColor = object.color
    }

  }

  remove () {
    let length = this.element.length
    for (let i = length - 1; i >= 0; i--) {
      this.element[i].parentNode.removeChild(this.element[i])
      this.element.splice(i, 1)
    }
  }
}

export default Snake
